package com.chahu.servlet.front;

import com.alibaba.fastjson.JSON;
import com.chahu.common.Result;
import com.chahu.entity.User;
import com.chahu.service.UserService;
import com.chahu.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    UserService userService;

    @Override
    public void init() throws ServletException {
        userService = new UserServiceImpl();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json; charset=utf-8");
        String nickname = req.getParameter("nickname");
        String phone = req.getParameter("phone");
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = new User();
        user.setNickname(nickname);
        user.setPhone(phone);
        user.setUsername(username);
        user.setPassword(password);
        user.setRole(0);
        
        System.out.println(user);
        System.out.println(user);
        System.out.println(user);
        try(PrintWriter writer = resp.getWriter()){
            if(userService.register(user, req.getSession())){
                writer.write(JSON.toJSONString(Result.success("注册成功")));
            }else {
                writer.write(JSON.toJSONString(Result.error("注册失败")));
            }
        }
    }
}
